package item;

import hibernateUtil.Playerinfo;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

import player.Player;

public class PlayerTransaction extends AbstractTransaction {
	
	protected Playerinfo player;
	protected String cause;
	protected List<GameItem> autoUseItems;
	protected boolean critical;
	
	public PlayerTransaction(Playerinfo player, String cause, boolean critical){
		this.player = player;
		this.state = ACTIVE;
		this.cause = cause;
		this.critical = critical;
		this.entities = new LinkedList<TransactionEntity>();
	}
	
	public boolean isCritical(){
		return critical;
	}
	
	public void internalCommit() throws TransactionException {
		if (state != ACTIVE)
			throw new TransactionException();
		for (TransactionEntity entity : entities) {
			entity.commit();
		}
	}
	
	public void internalRollback() throws TransactionException{
		if(state != ACTIVE)
			throw new TransactionException();
		for (TransactionEntity entity : entities) {
			entity.rollback();
		}
	}
	
	public void commit() throws TransactionException {
		player.release(this, true);
		this.state = COMMITED;
//		syncWithClient();
	}

	public void rollback() throws TransactionException {
		player.release(this, false);
		this.state = ROLLEDBACK;
	}

	public void syncWithClient(){
		if(this.state!=COMMITED)
			throw new IllegalStateException();
		for(TransactionEntity entity:entities){
			ChangedItem[] cis = entity.sync();
			if(cis!=null&&cis.length>0){
				for(int i=0;i<cis.length;i++){
					player.changed.addChangedItem(cis[i]);
				}
			}
		}
	}
	
	@Override
	public String toString(){
		StringBuilder sb = new StringBuilder();
		sb.append("[PLAYERTRANSACTION]");
		for(TransactionEntity entity:entities){
			sb.append(entity.toString());
		}
		return sb.toString();
	}
	
	public String getCause() {
		return cause;
	}
	
	public void setCause(String cause) {
		this.cause = cause;
	}
	
	public void addAutoUseItem(GameItem item) {
		if (autoUseItems == null) {
			autoUseItems = new ArrayList<GameItem>(3);
		}
		autoUseItems.add(item);
	}
	
	public List<GameItem> getAutoUseItems() {
		return autoUseItems;
	}

}

